//HashSet存储自定义类
package daily.may0514;

import java.util.HashSet;
import java.util.Objects;

class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
//重写equals方法
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return age == person.age &&
                Objects.equals(name, person.name);
    }
//重写hashCode方法
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
//重写toString方法，否则输出集合时打印的是地址值
    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

public class HashSetSavePersonClassTest {
    public static void main(String[] args) {
        HashSet<Person> set = new HashSet<>();
        Person p1 = new Person("张三李四",18);
        Person p2 = new Person("张三李四",19);
        Person p3 = new Person("王五赵六",18);
        Person p4 = new Person("王五赵六",18);
        System.out.println(p1.hashCode());//1635986589
        System.out.println(p2.hashCode());//1635986590
        System.out.println(p3.hashCode());//-2113219790
        System.out.println(p4.hashCode());//-2113219790
        //==比较的是地址值，不是哈希值
        System.out.println(p3==p4);//false，因为p3和p4是两个对象
        System.out.println(p3.equals(p4));//true
        set.add(p1);
        set.add(p2);
        set.add(p3);
        set.add(p4);
        //输出结果：[Person{name='王五赵六', age=18}, Person{name='张三李四', age=19}, Person{name='张三李四', age=18}]
        System.out.println(set);
    }
}
